<?php
namespace app\api\controller\v1;
use app\api\controller\Common;

class Client extends Common {
	var $modelDb;
	public function _initialize() {
		parent::_initialize();
		$this->modelDb = model("Client");
	}
	public function add_only() {
		$ids = $this->modelDb->insert($this->postData);
		if ($ids === false) {
			return $this->app_error($this->modelDb->getError());
		}
		return $this->app_success();
	}
	public function add() {
		$this->postData['userid'] = $this->uinfo['puserid'];
		$this->postData['brokerid'] = $this->uinfo['userid'];
		if ($this->postData['citycode']) {
			$info = explode(',', $this->postData['citycode']);
			$this->postData['province_code'] = $info[0];
			$this->postData['city_code'] = $info[1];
			$this->postData['area_code'] = $info[2];
		}
		$id = $this->modelDb->save_data($this->postData);
		if ($id === false) {
			return $this->app_error($this->modelDb->getError());
		}
		model('Statistics')->add_log($this->uinfo['userid'], 1, 1);
		return $this->app_success();
	}
	//获取客户列表
	public function client_list() {
		list($total, $list) = $this->modelDb->list_datas($this->postData, $this->uinfo);
		if ($list === false) {
			return $this->modelDb->app_error($this->modelDb->getError());
		}
		$lists = [];
		foreach ($list as $v) {
			$v['realname'] = $v['realname'];
			$lists[] = $v;
		}
		$pages = ceil($total / 10);
		return $this->app_success(['data' => $lists, 'pages' => $pages]);
	}
	public function get_clients() {
		$list = $this->modelDb->list_datas($this->postData, $this->uinfo['userid']);
		if ($list === false) {
			return $this->app_error($this->modelDb->getError());
		}
		return $this->app_success($list);
	}
	public function del_client() {
		$password = model('AdminUser')->where('userid', $this->uinfo['userid'])->value('password');
		if ($password != md5($this->postData['password'])) {
			return $this->app_error('登录密码错误');
		}
		$ids = $this->modelDb->where('id', $this->postData['id'])->delete();
		return $this->app_success();
	}
	//转交客户
	public function client_deliver() {
		$info = db('Client')->where('id', $this->postData['clientid'])->find();
		$data = [
			'userid' => $this->postData['userid'],
			'name' => $info['name'],
			'product' => $info['product'],
			'phone' => $info['phone'],
			'email' => $info['email'],
			'qq' => $info['qq'],
			'city' => $info['city'],
			'getdate' => $info['getdate'],
			'home' => $info['home'],
			'source' => $info['source'],
			'skilled' => $info['skilled'],
			'status' => $info['status'],
			'remark' => $info['remark'],
			'endtime' => $info['endtime'],
			'typeid' => $info['typeid'],
			'delitime' => SYS_TIME,
			'price' => $info['price'],
		];
		$ids = $this->modelDb->save_data($data);
		if ($ids === false) {
			return $this->app_error($this->modelDb->getError());
		}
		$this->modelDb->where('id', $this->postData['clientid'])->setField('transfer', 1);
		return $this->app_success();
	}
}